//
//  ZCOrderListBodyVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/2.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCOrderListBodyVC.h"

#import "ZCOrderListBodyTopCell.h"
#import "ZCOrderListBodyItemCell.h"
#import "ZCOrderListBodyBottmCell.h"

#import "ZCOrderViewModel.h"

#import "ZCOderReceiptVC.h"
#import "WZGLoginVC.h"
#import "ZCOrderCanselResionVC.h"
#import "ZCOrderConst.h"
#import "ZCOrderDetailVC.h"
#import "ZCLogisticsVC.h"
#import "ZCOrderListBodySearchView.h"

#import "ZCOrderPayVC.h"


@interface ZCOrderListBodyVC ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, copy) NSDictionary *editingDict;
@property (nonatomic, strong) ZCOrderListBodySearchView *searchView;
@end

@implementation ZCOrderListBodyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
  self.tableView.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xededed"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderListBodyBottmCell" bundle:nil]
         forCellReuseIdentifier:@"ZCOrderListBodyBottmCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderListBodyItemCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderListBodyItemCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderListBodyTopCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderListBodyTopCell"];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addHeaderRefreshWithCallBack:^{
        weakSelf.lastId = nil;
        [weakSelf.datasource removeAllObjects];
        if (weakSelf.refreshCallBack) {
            weakSelf.refreshCallBack(weakSelf.status,weakSelf.lastId);
        }
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (weakSelf.loadMoreCallBack) {
            weakSelf.loadMoreCallBack(weakSelf.status,weakSelf.lastId);
        }
    }];
    
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0,0,ScreenWidth,40}];
    ZCOrderListBodySearchView *view = [[ZCOrderListBodySearchView alloc] initWithFlex:nil Frame:headerView.bounds Owner:nil];
    view.frame = headerView.bounds;
    view.placehstr = @"订单号/商品名/姓名";
    [view setEndEditCallback:^(NSString * _Nonnull keywd) {
        [weakSelf.datasource removeAllObjects];
        weakSelf.searchCallBack(weakSelf.status, nil, keywd);
    }];
    [headerView addSubview:view];
    self.tableView.tableHeaderView = headerView;
    
    [self setTableView:self.tableView noDataWithTitle:@"您还没有相关的订单哦" des:nil andImageName:nil];
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dict = self.datasource[section];
    NSArray *orderExtend = [dict valueForKey:@"orderExtend"];
    return 2 + orderExtend.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSDictionary *dict = self.datasource[section];
    NSArray *orderExtend = [dict valueForKey:@"orderExtend"];
    if (row == 0) {
        ZCOrderListBodyTopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderListBodyTopCell"
                                                                       forIndexPath:indexPath];
        NSInteger type = [[dict valueForKey:@"type"] integerValue];
        if (type == 3) {
            cell.isGroupBuy = YES;
        } else {
            cell.isGroupBuy = NO;
        }
        cell.ordersn = [dict valueForKey:@"order_sn"];
        cell.statusName = [dict valueForKey:@"status_name"];
        return cell;
    } else if (row == orderExtend.count + 1) {
        ZCOrderListBodyBottmCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderListBodyBottmCell"
                                                                         forIndexPath:indexPath];
        cell.totalPrice = [dict valueForKey:@"actual_fee"];
        cell.status = [[dict valueForKey:@"status"] intValue];
        cell.order_type = [[dict valueForKey:@"type"] intValue];
        cell.otherpay_uid = [dict valueForKey:@"otherpay_uid"];
        cell.otherpay_avatar = [dict valueForKey:@"otherpay_avatar"];
        [self configBottomCellAction:cell orderInfo:dict];
        return cell;
    } else {
        ZCOrderListBodyItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderListBodyItemCell"
                                                                        forIndexPath:indexPath];
        cell.dict = orderExtend[row - 1];
        cell.recever = @[[dict valueForKey:@"receiver_name"],[dict valueForKey:@"receiver_mobile"]];
        return cell;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
  v.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xf8f8fc"];
    return v;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 110.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSDictionary *dict = self.datasource[section];
    NSArray *orderExtend = [dict valueForKey:@"orderExtend"];
   
    if (row == 0 || row == orderExtend.count + 1) {
        return 50.0f;
    } else {
        return UITableViewAutomaticDimension;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSDictionary *dict = self.datasource[section];
    
    ZCOrderDetailVC *vc = [[ZCOrderDetailVC alloc] init];
    vc.ids = [dict valueForKey:@"id"];
    vc.referrer_uid = [dict valueForKey:@"referrer_uid"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setItems:(NSArray *)items {
    _items = items;
    [self.datasource addObjectsFromArray:items];
}

- (void)reloadDataWithSearch:(BOOL)isSearch {
    [self.tableView endHeaderRefreshing];
    [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];

}

- (void)beginRefresh {
    if (self.lastId == nil) {
        self.lastId = nil;
        [self.datasource removeAllObjects];
        self.refreshCallBack(self.status,self.lastId);
    } else {
        [self.tableView reloadData];
    }
}

- (void)configBottomCellAction:(ZCOrderListBodyBottmCell *)cell orderInfo:(NSDictionary *)info {
    __weak typeof(self) weakSelf = self;
    
    switch (cell.status) {
        case STATUS_CANCEL:{
            
        } break;
        case STATUS_WAIT_PAY:{
            [cell setBtn01ClickCallBack:^{ //取消订单
                [weakSelf canselOrder:info];
            }];
            [cell setBtn02ClickCallBack:^{ //删除订单
                [weakSelf removeOrder:info];
            }];
            [cell setBtn03ClickCallBack:^{ //立即支付
                NSInteger goods_sale_type = [[info valueForKey:@"goods_sale_type"] integerValue];
                if (goods_sale_type == 1) {
                    [weakSelf.view makeToast:@"啊哦,该商品已下架,不能支付了" duration:2.0 position:CSToastPositionCenter];
                } else {
                    ZCOrderPayVC *vc = [[ZCOrderPayVC alloc] init];
                    vc.isOrderList = YES;
                    __block NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:info];
                    [dict setValue:[info valueForKey:@"id"] forKey:@"order_id"];
                    vc.dict = dict;
                    vc.isOrderList = YES;
                    [vc setCallback:^(BOOL status) {
                        if (status) {
                            for (NSDictionary *dd in weakSelf.datasource) {
                                if ([[dd valueForKey:@"id"] intValue] == [[dict valueForKey:@"id"] intValue]) {
                                    [weakSelf.datasource removeObject:dd];
                                    [weakSelf reloadDataWithSearch:NO];
                                    break;
                                }
                            }
                            if (weakSelf.needUpdateData) { //刷新其他的
                                weakSelf.needUpdateData(weakSelf.status);
                            }
                        }
                    }];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }];
        } break;
        case STATUS_WAIT_SEND:{
            [cell setBtn03ClickCallBack:^{ //取消订单
                NSInteger type = [[info valueForKey:@"type"] integerValue];
                if (type == 3) { //拼团订单不可以取消
                    [weakSelf.view makeToast:@"拼团订单不可取消" duration:2.0 position:CSToastPositionCenter];
                    return;
                }
                [weakSelf canselOrder:info];
            }];
            
            [cell setBtn02ClickCallBack:^{ //订单回执
                [weakSelf pushOderReceiptWithOrderInfo:info];
            }];
        } break;
        case STATUS_WAIT_GET:{
            [cell setBtn01ClickCallBack:^{ //订单回执
                [weakSelf pushOderReceiptWithOrderInfo:info];
            }];
            [cell setBtn02ClickCallBack:^{ //查看物流
                ZCLogisticsVC *vc = [[ZCLogisticsVC alloc] init];
                vc.logisticId = [info valueForKey:@"logistics_sn"];
                vc.expressId = [info valueForKey:@"express_code"];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            [cell setBtn03ClickCallBack:^{ //确认收货
                __weak typeof(self) weakSelf = self;
                [self showAlert:@"提示" content:@"是否确认收货" actionStr1:@"确认" style:UIAlertActionStyleDefault actionAc1:^(UIAlertAction * _Nonnull action) {
                    [weakSelf netConfirmReceiptWithInfo:info];
                } actionStr2:@"取消" style:UIAlertActionStyleCancel actionAc:^(UIAlertAction * _Nonnull action) {
                    
                }];
            }];
        } break;
        case STATUS_WAIT_FEEDBACK:{
            [cell setBtn01ClickCallBack:^{ //订单回执
                [weakSelf pushOderReceiptWithOrderInfo:info];
            }];
//            [cell setBtn02ClickCallBack:^{ //评价
//                ZCCommentVC *vc = [[ZCCommentVC alloc] init];
//                [self.navigationController pushViewController:vc animated:YES];
//            }];
            [cell setBtn03ClickCallBack:^{ //再次购买
//                WZGGoodsDetailVC *vc = [[WZGGoodsDetailVC alloc] init];
//                vc.idstr = [info valueForKey:@"goods_id"];
//                [weakSelf.parentViewController.navigationController pushViewController:vc animated:YES];
            }];

        } break;
        case STATUS_END:{
            [cell setBtn01ClickCallBack:^{ //订单回执
                [weakSelf pushOderReceiptWithOrderInfo:info];
            }];
//            [cell setBtn02ClickCallBack:^{ //查看评价
//                ZCCommentVC *vc = [[ZCCommentVC alloc] init];
//                [self.navigationController pushViewController:vc animated:YES];
//            }];
            [cell setBtn03ClickCallBack:^{ //再次购买
//                WZGGoodsDetailVC *vc = [[WZGGoodsDetailVC alloc] init];
//                vc.idstr = [info valueForKey:@"goods_id"];
//                [weakSelf.parentViewController.navigationController pushViewController:vc animated:YES];
            }];
        } break;
        case STATUS_AFTER_SALES:{} break;
        case STATUS_CLOSE:{
            [cell setBtn02ClickCallBack:^{ //删除订单
                [weakSelf removeOrder:info];
            }];
            [cell setBtn03ClickCallBack:^{ //重新购买
//                WZGGoodsDetailVC *vc = [[WZGGoodsDetailVC alloc] init];
//                vc.idstr = [info valueForKey:@"goods_id"];
//                [weakSelf.parentViewController.navigationController pushViewController:vc animated:YES];
            }];
            
        } break;
        default:
            break;
    }
}

//MARK:订单回执
- (void)pushOderReceiptWithOrderInfo:(NSDictionary *)info{
   ZCOderReceiptVC *vc = [[ZCOderReceiptVC alloc] init];
   vc.ids = [info valueForKey:@"id"];
   [generalToolBox setVcViewAlpha:vc withAlpha:0.6];
   [self presentViewController:vc animated:YES completion:nil];
}


- (void)updateDataSource {
    self.lastId = nil;
    [self.datasource removeAllObjects];
    [self beginRefresh];
}

// MARK: - Action

- (void)canselOrder:(NSDictionary *)orderInfo {
    self.editingDict = orderInfo;
    [self netFetchOrderCanselResion];
}

- (void)removeOrder:(NSDictionary *)orderInfo {
    __weak typeof(self) weakSelf = self;
    [self showAlert:@"提示" content:@"确定要删除吗?" actionStr1:@"取消" style:UIAlertActionStyleDefault actionAc1:^(UIAlertAction * _Nonnull action) {
        
    } actionStr2:@"删除" style:UIAlertActionStyleDestructive actionAc:^(UIAlertAction * _Nonnull action) {
        [weakSelf netRemoveOrderWithId:[orderInfo valueForKey:@"id"]];
    }];
}

// MARK: - NET

- (void)netFetchOrderCanselResion {
    __weak typeof(self) weakSelf = self;
    [ZCOrderViewModel fetchOrderCanselResionWithComplete:^(ZCErrorCode status, NSString *message, id data) {
        ZCOrderCanselResionVC *vc = [[ZCOrderCanselResionVC alloc] init];
        weakSelf.definesPresentationContext = YES;
        [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
        vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        vc.items = data;
        [vc setDoneCallback:^(NSDictionary *dict) {
            [weakSelf netCanselOrderWithId:[[weakSelf.editingDict valueForKey:@"id"] stringValue]
                                   causeId:[dict valueForKey:@"id"]];
        }];
        [weakSelf.view.window.rootViewController presentViewController:vc animated:YES completion:^{
            [UIView animateWithDuration:0.3 animations:^{
                vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
            }];
        }];
    }];
}

- (void)netRemoveOrderWithId:(NSString *)idstr {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel delOrderWithId:idstr complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSInvalidTokenError) {
            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
            [vc setGoodsVCCallBack:^(NSInteger type) {
                [weakSelf beginRefresh];
            }];
            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
            [weakSelf.parentViewController.navigationController presentViewController:nvc animated:YES completion:nil];
        } else if (status == kHXSNoError) {
            [weakSelf beginRefresh];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netCanselOrderWithId:(NSString *)idstr causeId:(NSString *)causeId {
    __weak typeof(self) weakSelf = self;
    [ZCOrderViewModel canselOrderWithId:idstr causeId:causeId complete:^(ZCErrorCode status, NSString *message, id data) {
        if (status == kHXSInvalidTokenError) {
            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
            [vc setGoodsVCCallBack:^(NSInteger type) {
                [weakSelf beginRefresh];
            }];
            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
            [weakSelf.parentViewController.navigationController presentViewController:nvc animated:YES completion:nil];
        } else if (status == kHXSNoError) {
            for (NSDictionary *dict in weakSelf.datasource) {
                if ([[[dict valueForKey:@"id"] stringValue] isEqualToString:idstr]) {
                    [weakSelf.datasource removeObject:dict];
                    [weakSelf reloadDataWithSearch:NO];
                    break;
                }
            }
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netConfirmReceiptWithInfo:(NSDictionary *)info {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [ZCOrderViewModel confirmreceiptWithOrderId:[info valueForKey:@"id"] complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            [weakSelf.view makeToast:@"签收成功" duration:2.0 position:CSToastPositionCenter];
            // 修改界面
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                for (NSDictionary *dict in weakSelf.datasource) {
                    if ([[dict valueForKey:@"id"] integerValue] == [[info valueForKey:@"id"] integerValue]) {
                        [weakSelf.datasource removeObject:dict];
                        [weakSelf reloadDataWithSearch:NO];
                        break;
                    }
                }
            });
            // 去评价
            [self showAlert:@"" content:@"亲，您当前订单已完成，\n请进行评价～" actionStr1:@"取消" style:UIAlertActionStyleDefault actionAc1:^(UIAlertAction * _Nonnull action) {

            } actionStr2:@"去评价" style:UIAlertActionStyleDestructive actionAc:^(UIAlertAction * _Nonnull action) {
                // 评价
//                WZGAddCommentVC *addCommentVC = [[WZGAddCommentVC alloc] init];
//                WZGCommentOrderModel *orderItem = [[WZGCommentOrderModel alloc] init];
//                orderItem.order_id = [info valueForKey:@"id"];
//                addCommentVC.isSaleAfter = false;
//                addCommentVC.orderItem = orderItem;
//                [weakSelf.navigationController pushViewController:addCommentVC animated:true];
            }];

        } else if (status == kHXSInvalidTokenError) {
            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
            [vc setGoodsVCCallBack:^(NSInteger type) {
                
            }];
            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

// MARK: - GET

- (NSMutableArray *)datasource {
    if (_datasource == nil) {
        _datasource = [NSMutableArray new];
    }
    return _datasource;
}

@end
